# -*- coding: utf-8 -*-
'''手动开奖，运行方式为 python manual_apply_winner.py cq_ssc 20170301022
    后面是期号
'''
import os
import sys
import traceback

base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(base_dir)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "base.settings")

from common.lottery.cyclical import ORDER_STATUS, ACTIVITY_STATUS
from common.lottery.cyclical.model import ACTIVITY_MODEL, ORDER_LOGIC, ORDER_MODEL
from common.lottery import KEYWORD_TYPE_DCT
from common.lottery.cyclical.abstract.order import WinOrderApplyer


def run(key, term):
    activity_type = KEYWORD_TYPE_DCT[key]
    ac_table = ACTIVITY_MODEL[activity_type]
    logic = ORDER_LOGIC[activity_type]
    ac = ac_table.query.filter(ac_table.term == term).one()
    applyer = WinOrderApplyer(term, ac.number, logic, activity_type)

    applyer.apply()


def run_all(key):
    activity_type = KEYWORD_TYPE_DCT[key]
    ac_table = ACTIVITY_MODEL[activity_type]
    order_table = ORDER_MODEL[activity_type]
    query = order_table.query.filter(order_table.status == ORDER_STATUS.READY).all()
    logic = ORDER_LOGIC[activity_type]
    for item in query:
        ac = ac_table.query.filter(ac_table.term == item.term).filter(
            ac_table.status == ACTIVITY_STATUS.ANNOUNCED).first()
        if ac:
            print('apply %s ...' % item.term)
            applyer = WinOrderApplyer(item.term, ac.number, logic, activity_type)
            applyer.apply()
        else:
            print('term not found: %s' % item.term)


if __name__ == '__main__':
    try:
        lottery_key = sys.argv[1]
        lottery_term = sys.argv[2]
        if lottery_term == 'all':
            run_all(lottery_key)
        else:
            run(lottery_key, lottery_term)
    except Exception as e:
        print e
        print traceback.print_exc()
